package org.wcms.surrounded.persistence;

import java.util.List;

import org.wcms.surrounded.model.Record;
import org.wcms.surrounded.model.User;

import com.google.inject.Inject;
import com.googlecode.objectify.Objectify;

public class RecordService {

    final private Objectify service;
    
    @Inject
    public RecordService(Objectify service) {
        this.service = service;
    }
    
    public void addRecord(User user, int score) {
        
        int numberOfUserRecords = service
                .query(Record.class)
                .filter("userId", user.getId()).count();
        
        // TODO if there are more than 10 only the 10th result is removed
        if (numberOfUserRecords >= 10) {
            Record removedRecord = service
                        .query(Record.class)
                        .filter("userId", user.getId())
                        .order("-score")
                        .offset(9).get();

            if (removedRecord.getScore() < score) {
                service.delete(removedRecord);
            } else {
                return;
            }
        }
        
        Record record = new Record();
        record.setUserId(user.getId());
        record.setScore(score);
        
        service.put(record);
    }
    
    public Record getRecordByUser(User user) {    	
    	return service
    	        .query(Record.class)
    	        .filter("userId", user.getId())
    	        .order("-score")
    	        .limit(1).get();    	    	    	
    }
    
    public List<Record> getTopTenRecords() {
        return service
                .query(Record.class)
                .order("-score")
                .limit(10).list();
    }
    
    public void transferScoresToRegisteredUser(User oldSimpleUser, User newRegisteredUser)
    {
    	List<Record> oldUserRecords = service.query(Record.class).filter("userId", oldSimpleUser.getId()).list();
    	
    	for (Record oldUserRecord : oldUserRecords)    	{
    		
    		Record newUserRecord = new Record();
    		newUserRecord.setUserId(newRegisteredUser.getId());
    		newUserRecord.setScore(oldUserRecord.getScore());
    		service.put(newUserRecord);
    		
    		service.delete(oldUserRecord);
    	}    	
    }
}
